package org.lundberg.podcasts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;

public class IntentHandler extends BroadcastReceiver
{
	public static final int PREVIOUS = 0;
	public static final int FORWARD = 1;
	
	@Override
	public void onReceive(Context context, Intent intent)
	{
		Log.d("IntentHandler", "received "+intent.getAction());
		
    	if ("android.media.AUDIO_BECOMING_NOISY".equals(intent.getAction()))
    	{
    		Intent serviceIntent = new Intent(PlayerService.STOP);
			context.sendBroadcast(serviceIntent);
    	}
    	else if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction()))
    	{
    		KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
    		
    		if (event == null) {
    			return;
    		}
    		
    		if (event.getAction() == KeyEvent.ACTION_DOWN)
    		{
    			Log.d("IntentHandler", "and keyEvent: "+event);
    			
    			Intent serviceIntent = new Intent();
    			
    			switch (event.getKeyCode())
    			{
    				case KeyEvent.KEYCODE_HEADSETHOOK:
    								serviceIntent.putExtra("headset", true);
    				case KeyEvent.KEYCODE_MEDIA_PLAY:
    				case KeyEvent.KEYCODE_MEDIA_PAUSE:
    				case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
									serviceIntent.setAction(PlayerService.PLAY_OR_STOP);									
									break;
    												
    				case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
    								serviceIntent.setAction(PlayerService.SEEK);
    								serviceIntent.putExtra("direction", IntentHandler.PREVIOUS);
									break;
									
    				case KeyEvent.KEYCODE_MEDIA_NEXT:
    								serviceIntent.setAction(PlayerService.SEEK);
				        			serviceIntent.putExtra("direction", IntentHandler.FORWARD);
									break;
    			}
    			
    			context.sendBroadcast(serviceIntent);
    		}
    		
    	}
    	else if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
		{
    		Intent updateServiceIntent = new Intent(context, UpdateService.class);
            updateServiceIntent.putExtra("update", false);
            context.startService(updateServiceIntent);
		}
    	else if (UpdateService.CLEARED.equals(intent.getAction()))
    	{
    		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    		Editor editor = settings.edit();
        	editor.putInt(PodcastPreferenceActivity.NEW_ITEM_COUNT_PREF, 0);
        	editor.commit();
    	}
	}

}
